import java.util.LinkedList;
import java.util.Queue;

import javax.swing.tree.TreeNode;

/*
 * @lc app=leetcode.cn id=513 lang=java
 *
 * [513] 找树左下角的值
 */

// @lc code=start
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    int maxD=Integer.MIN_VALUE;
    int maxLeftVal;
    public int findBottomLeftValue(TreeNode root) {
        // //层次遍历
        // Queue<TreeNode> que=new LinkedList<>();
        // que.add(root);
        // int res=0;
        // while(!que.isEmpty()){
        //     int size=que.size();
        //     for(int i=0;i<size;i++){
        //         TreeNode front=que.poll();
        //         if(i==0){
        //             res=front.val;
        //         }
        //         if(front.left!=null) que.offer(front.left);
        //         if(front.right!=null) que.offer(front.right);
        //     }
        // }
        // return res;
        dfs(root, 0);
        return maxLeftVal;
    }
    public void dfs(TreeNode root,int depth){
        //递归退出：找到最下面的页子节点
        if(root.left==null&&root.right==null){
            if(depth>maxD){
                maxD=depth;
                maxLeftVal=root.val;
            }
            return;
        }
        //递归操作
        if(root.left!=null){
            dfs(root.left, depth+1);
        }
        if(root.right!=null){
            dfs(root.right, depth+1);
        }
        return;
    }
}
// @lc code=end

